package dai.samples.shiro.config.session.scheduler;

import dai.samples.shiro.config.session.dao.MySessionDAO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * 缓存验证器
 *
 */
public class MyValidatingSessionManager extends DefaultWebSessionManager {

    /**
     *  SessionDAO 接口的实现
     */
    private MySessionDAO sessionDAO;


    private static final Logger log = LoggerFactory.getLogger(DefaultWebSessionManager.class);

    /**
     * 这里是执行session删除的操作
     */
    @Override
    public void validateSessions() {

        log.info("执行了 validateSessions ");
        if (log.isInfoEnabled()) {
            log.info("Validating all active sessions...");
        }

        // 这里可以实现自己的业务逻辑
        Collection<Session> sessions = sessionDAO.getActiveSessions();

        int invalidCount = sessions.size();
        if (CollectionUtils.isNotEmpty(sessions)) {
            sessions.forEach(item -> {
                // TODO 此时从session中定义自己的业务逻辑进行session移除
                // 使用sessionDAO清理数据库中过期数据
                //sessionDAO.delete(item);
            });
        }

        if (log.isInfoEnabled()) {
            String msg = "Finished session validation.";
            if (invalidCount > 0) {
                msg = msg + "  [" + invalidCount + "] sessions were stopped.";
            } else {
                msg = msg + "  No sessions were stopped.";
            }

            log.info(msg);
        }

    }

    public void setSessionDAO(MySessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

}
